import time
import numpy as np
from vpython import *

scene.height=880
scene.width=1890
m1=random()*1000
m2=random()*1000
m3=random()*1000
b1 = sphere(pos=vector(random(),random(),random()),radius = (3/40/np.pi*m1)**(1/3),color=color.red,make_trail=True,trail_radius=1)  #定义球的大小和颜色
b2 = sphere(pos=vector(random(),random(),random()), radius = (3/40/np.pi*m2)**(1/3),color=color.blue,make_trail=True,trail_radius=1)  #定义球的大小和颜色
b3 = sphere(pos=vector(random(),random(),random()), radius = (3/40/np.pi*m3)**(1/3),color=color.green,make_trail=True,trail_radius=1)  #定义球的大小和颜色
b1v=[random(),random(),random()]
b2v=[random(),random(),random()]
b3v=[random(),random(),random()]
print(b1v,"    ",b2v,"    ",b3v)
f1=(0,0,0)  # r→g:F1
f2=(0,0,0)  # r→b:F2
f3=(0,0,0)  # g→b:F3
dt=1/100
i=0

while 1:
    l1 = curve(b1.pos, b2.pos,radius=1)
    l2 = curve(b1.pos, b3.pos,radius=1)
    l3 = curve(b2.pos, b3.pos,radius=1)
    time.sleep(dt)
    v1 = (b2.pos.x-b1.pos.x,b2.pos.y-b1.pos.y,b2.pos.z-b1.pos.z)
    v2 = (b3.pos.x - b1.pos.x, b3.pos.y - b1.pos.y, b3.pos.z - b1.pos.z)
    v3 = (b3.pos.x - b2.pos.x, b3.pos.y - b2.pos.y, b3.pos.z - b2.pos.z)
    r1 = (v1[0] ** 2+v1[1]**2+v1[2]**2)**0.5
    r2 = (v2[0] ** 2 + v2[1] ** 2 + v2[2] ** 2) ** 0.5
    r3 = (v3[0] ** 2 + v3[1] ** 2 + v3[2] ** 2) ** 0.5

    F1 = 6.67 * m1 * m2 / r1
    F2 = 6.67 * m1 * m3 / r2
    F3 = 6.67 * m2 * m3 / r3

    b1v[0] += (F1 * v1[0] / r1 + F2 * v2[0] / r2) / m1 * dt
    b1v[1] += (F1 * v1[1] / r1 + F2 * v2[1] / r2) / m1 * dt
    b1v[2] += (F1 * v1[2] / r1 + F2 * v2[2] / r2) / m1 * dt
    b2v[0] += (F1 * (-v1[0]) / r1 + F3 * v3[0] / r3) / m2 * dt
    b2v[1] += (F1 * (-v1[1]) / r1 + F3 * v3[1] / r3) / m2 * dt
    b2v[2] += (F1 * (-v1[2]) / r1 + F3 * v3[2] / r3) / m2 * dt
    b3v[0] += (F2 * (-v2[0]) / r2 + F3 * (-v3[0]) / r3) / m3 * dt
    b3v[1] += (F2 * (-v2[1]) / r2 + F3 * (-v3[1]) / r3) / m3 * dt
    b3v[2] += (F2 * (-v2[2]) / r2 + F3 * (-v3[2]) / r3) / m3 * dt

    b1.pos.x += b1v[0] * dt
    b1.pos.y += b1v[1] * dt
    b1.pos.z += b1v[2] * dt
    b2.pos.x += b2v[0] * dt
    b2.pos.y += b2v[1] * dt
    b2.pos.z += b2v[2] * dt
    b3.pos.x += b3v[0] * dt
    b3.pos.y += b3v[1] * dt
    b3.pos.z += b3v[2] * dt
    l1.clear()
    l2.clear()
    l3.clear()
    i+=1
    scene.title="b1:"+str((round(b1.pos.x,1),round(b1.pos.y,1),round(b1.pos.z,1)))+"   b2:"+str((round(b2.pos.x,1),round(b2.pos.y,1),round(b2.pos.z,1)))+"   b3:"+str((round(b3.pos.x,1),round(b3.pos.y,1),round(b3.pos.z,1)))
    # if i % 600 == 0:
    #     scene.camera.follow(b1)
    # if i % 600 == 200:
    #     scene.camera.follow(b2)
    # if i % 600 == 400:
    #     scene.camera.follow(b3)
    scene.caption=("Distance R ↔ B ：" +str(round(r1,1)))
    scene.append_to_caption("       Distance R ↔ G ：" + str(round(r2,1)))
    scene.append_to_caption("       Distance B ↔ G ：" + str(round(r3,1)))

